package org.jeecg.modules.rental.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.boot.starter.lock.client.RedissonLockClient;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.rental.vo.LoginRentalAccount;
import org.jeecg.common.util.RedisUtil;
//import org.jeecg.jt808.Jt808Control.Jt808CentralControlConfig;
//import org.jeecg.jt808.modbus.ModbusParams;
//import org.jeecg.jt808.processor.JT808MessageProcessor;
//import org.jeecg.jt808.processor.MessageType;
//import org.jeecg.mapper.*;
//import org.jeecg.mqtt.feign.IControlAPI;
//import org.jeecg.service.IEquService;
import org.jeecg.jt808.Jt808Control.Jt808CentralControlConfig;
import org.jeecg.jt808.modbus.ModbusParams;
import org.jeecg.jt808.processor.JT808MessageProcessor;
import org.jeecg.jt808.processor.MessageType;
import org.jeecg.modules.iot.api.IControlAPI;
import org.jeecg.modules.rental.entity.RentalAccountPackage;
import org.jeecg.modules.rental.entity.RentalEBike;
import org.jeecg.modules.rental.mapper.RentalAccountMapper;
import org.jeecg.modules.rental.mapper.RentalAccountPackageMapper;
import org.jeecg.modules.rental.mapper.RentalEBikeMapper;
import org.jeecg.modules.rental.mapper.RentalStoreMapper;
import org.jeecg.modules.rental.service.IEquService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
//import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class EquServiceImpl implements IEquService {


    @Autowired
    private RentalStoreMapper chargeMeshPointMapper;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
    @Autowired
    private IControlAPI iControlAPI;
    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private RentalEBikeMapper rentalCarMapper;
    @Resource
    private RentalAccountMapper rentalPayAccountMapper;
    @Resource
    private RentalAccountPackageMapper rentalAccountPackageMapper;
    @Autowired
    private MessageSource messageSource;


    private static final String NATIONAL_STANDARD_SPEED_LIMIT_KEY = "vehicle:%s:nationalStandardSpeedLimit"; //  Redis key 格式


//
//    @Override
//    public Result<List<RentalStorePoint>> mapListEquPoint(String latitude, String longitude, String accountId) {
//        if (latitude!=null&&latitude.equals("")||longitude!=null&&longitude.equals("")){
//            throw new JeecgBootException("经纬度信息有误");
//        }
//        return Result.OK(chargeMeshPointMapper.getMapInfo(latitude,longitude));
//    }
//
//    @Override
//    public Result<List<OpenedCitiesRsp>> openedCities(String accountId) {
//        return Result.OK(chargeMeshPointMapper.openedCities());
//    }


    /*-------------------------------------------------------------------------------------------------------------------------------------*/
    /*车辆操作部分*/
    @Override
    public Boolean openCar(RentalAccountPackage rentalAccountPackage) {
        //JT808Processor processor = new VehicleControlProcessor();
        RentalAccountPackage accountPackage = rentalAccountPackageMapper.selectById(rentalAccountPackage.getId());
        if (accountPackage != null) {
            if (accountPackage.getCarId() != null) {
                Boolean isOpen = false;
                try {
                    RentalEBike car = rentalCarMapper.selectById(accountPackage.getCarId());
                    JT808MessageProcessor jt808MessageProcessor = new JT808MessageProcessor();
                    String controlStr = jt808MessageProcessor.process(car.getCarCode(), car.getPhone(), MessageType.OPEN_CAR);
                    kafkaTemplate.send("device_send", car.getCarCode(), controlStr);

                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return isOpen;
            }
        }
        return false;
    }

    @Override
    public Boolean openManageCar(Long carId) {
        Boolean isOpen = false;
        RentalEBike car = rentalCarMapper.selectById(carId);
        if (car != null) {
            JT808MessageProcessor jt808MessageProcessor = new JT808MessageProcessor();
            String controlStr = jt808MessageProcessor.process(car.getCarCode(), car.getPhone(), MessageType.OPEN_CAR);
            /*kafkaTemplate.send("device_send", car.getCarCode(), controlStr);
            sendCommandViaKafka( car.getCarCode() , car.getPhone(), MessageType.OPEN_CAR);*/
            //isOpen=  iControlAPI.openCar(car.getCarCode(),car.getPhone());

            sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.OPEN_CAR);
        }
        return isOpen;
    }

    @Override
    public Boolean closeCar(RentalAccountPackage rentalAccountPackage) {
        RentalAccountPackage accountPackage = rentalAccountPackageMapper.selectById(rentalAccountPackage.getId());
        if (accountPackage != null) {
            if (accountPackage.getCarId() != null) {
                Boolean isOpen = true;
                try {
                    RentalEBike car = rentalCarMapper.selectById(accountPackage.getCarId());
                    /* isOpen=  iControlAPI.closeCar(car.getCarCode(),car.getPhone());*/
                    sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.CLOSE_CAR);

                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return isOpen;
            }

        }
        return false;
    }


    @Override
    public Boolean closeManageCar(Long carId) {
        Boolean isOpen = true;
        RentalEBike car = rentalCarMapper.selectById(carId);
        if (car != null) {
            /* isOpen = iControlAPI.closeCar(car.getCarCode(),car.getPhone());*/
            sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.CLOSE_CAR);
        }
        return isOpen;
    }

    @Override
    public Boolean defenseCar(RentalAccountPackage rentalAccountPackage) {
        RentalAccountPackage accountPackage = rentalAccountPackageMapper.selectById(rentalAccountPackage.getId());
        if (accountPackage != null) {
            if (accountPackage.getCarId() != null) {
                Boolean isMeasures = false;
                try {
                    RentalEBike car = rentalCarMapper.selectById(accountPackage.getCarId());
                    /*isMeasures=  iControlAPI.defenseCar(car.getCarCode(),car.getPhone());*/
                    isMeasures = sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.DEFENSE_CAR);

                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return isMeasures;
            }

        }
        return false;
    }

    @Override
    public Boolean defenseManageCar(Long carId) {
        Boolean isMeasures = false;
        try {
            RentalEBike car = rentalCarMapper.selectById(carId);
            if (car != null) {
                /*isMeasures = iControlAPI.defenseCar(car.getCarCode(),car.getPhone());*/
                isMeasures = sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.DEFENSE_CAR);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return isMeasures;
    }


    @Override
    public Boolean disarmingCar(RentalAccountPackage rentalAccountPackage) {
        RentalAccountPackage accountPackage = rentalAccountPackageMapper.selectById(rentalAccountPackage.getId());
        if (accountPackage != null) {
            if (accountPackage.getCarId() != null) {
                Boolean isDisarming = false;
                try {
                    RentalEBike car = rentalCarMapper.selectById(accountPackage.getCarId());
                    /*isDisarming=  iControlAPI.disarmingCar(car.getCarCode(),car.getPhone());*/
                    isDisarming = sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.DISARMING_CAR);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return isDisarming;
            }

        }
        return false;
    }


    @Override
    public Boolean disarmingManageCar(Long carId) {
        Boolean isDisarming = false;
        try {
            RentalEBike car = rentalCarMapper.selectById(carId);
            if (car != null) {
                /* isDisarming = iControlAPI.disarmingCar(car.getCarCode(),car.getPhone());*/
                isDisarming = sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.DISARMING_CAR);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return isDisarming;
    }

    @Override
    public Boolean handleLockOpen(RentalAccountPackage rentalAccountPackage) {
      /*  RentalEBike carTest=new RentalEBike();
        //carTest.setCarCode("869583076506984");
        //carTest.setPhone("583076506984");

        carTest.setCarCode("869583076507735");
        carTest.setPhone("583076507735");
        carService.handleLockOpen(carTest);*/
        RentalAccountPackage accountPackage = rentalAccountPackageMapper.selectById(rentalAccountPackage.getId());
        if (accountPackage != null) {
            if (accountPackage.getCarId() != null) {
                Boolean isHandleLockOpen = false;
                try {
                    RentalEBike car = rentalCarMapper.selectById(accountPackage.getCarId());
                    /*isHandleLockOpen=  iControlAPI.handleLockOpen(car.getCarCode(),car.getPhone());*/

                    isHandleLockOpen = sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.HANDLE_LOCK_OPEN);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return isHandleLockOpen;
            }

        }

        return true;
    }

    @Override
    public Boolean handleManageLockOpen(Long carId) {
        Boolean isHandleLockOpen = false;
        try {
            RentalEBike car = rentalCarMapper.selectById(carId);
            //isHandleLockOpen=  iControlAPI.handleLockOpen(car.getCarCode(),car.getPhone());
            isHandleLockOpen = sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.HANDLE_LOCK_OPEN);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return isHandleLockOpen;
    }

    @Override
    public boolean getSportModeStatus(RentalEBike car) {
        try {
            // 通过 Feign 客户端调用远程接口
            return iControlAPI.getSportModeStatus(car.getCarCode(), car.getPhone());

        } catch (Exception e) {
            // 处理异常，例如记录日志或返回默认值··
            log.error("获取运动模式状态失败", e);
            return false; // 或返回默认值，例如 false
        }
    }


    @Override
    public Boolean handleManageLockClose(Long carId) {
        Boolean isHandleLockOpen = false;
        try {
            RentalEBike car = rentalCarMapper.selectById(carId);
            //isHandleLockOpen=  iControlAPI.handleLockClose(car.getCarCode(),car.getPhone());
            isHandleLockOpen = sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.HANDLE_LOCK_OPEN);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return isHandleLockOpen;
    }

    @Override
    public Boolean pairRemoteControl(Long carId) {
        Boolean isPaired = false;
        try {
            // 根据 carId 获取车辆信息
            RentalEBike car = rentalCarMapper.selectById(carId);
            if (car != null) {
                // 调用 carService 中的 pairRemoteControl 方法
                //isPaired = iControlAPI.pairRemoteControl(car.getCarCode(), car.getPhone());
                isPaired = sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.REMOTE_CONTROL_PAIR);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return isPaired;
    }

    @Override
    public Boolean clearRemoteControl(Long carId) {
        Boolean isCleared = false;
        try {
            // 根据 carId 获取车辆信息
            RentalEBike car = rentalCarMapper.selectById(carId);
            if (car != null) {
                // 调用 carService 中的 clearRemoteControl 方法
                isCleared = iControlAPI.clearRemoteControl(car.getCarCode(), car.getPhone());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return isCleared;
    }

    @Override
    public Boolean handleLockClose(RentalAccountPackage rentalAccountPackage) {
       /* RentalEBike carTest=new RentalEBike();
        //carTest.setCarCode("869583076506984");
        //carTest.setPhone("583076506984");

         carTest.setCarCode("869583076507735");
         carTest.setPhone("583076507735");
        carService.handleLockClose(carTest);*/
        RentalAccountPackage accountPackage = rentalAccountPackageMapper.selectById(rentalAccountPackage.getId());
        if (accountPackage != null) {
            if (accountPackage.getCarId() != null) {
                Boolean isHandleLockClose = false;
                try {
                    RentalEBike car = rentalCarMapper.selectById(accountPackage.getCarId());
                    //isHandleLockClose=  iControlAPI.handleLockClose(car.getCarCode(),car.getPhone());
                    sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.HANDLE_LOCK_CLOSE);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return isHandleLockClose;
            }

        }
        return true;
    }

    @Override
    public Boolean searchCar(RentalAccountPackage rentalAccountPackage) {
        RentalAccountPackage accountPackage = rentalAccountPackageMapper.selectById(rentalAccountPackage.getId());
        if (accountPackage != null) {
            if (accountPackage.getCarId() != null) {
                Boolean isSearch = false;
                try {
                    RentalEBike car = rentalCarMapper.selectById(accountPackage.getCarId());
                    //isSearch=  iControlAPI.searchCar(car.getCarCode(),car.getPhone());
                    isSearch = sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.SEARCH_CAR);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return isSearch;
            }

        }
        return false;
    }

    @Override
    public Boolean searchManageCar(Long carId) {
        Boolean isSearch = false;
        try {
            RentalEBike car = rentalCarMapper.selectById(carId);
            if (car != null) {
                //isSearch=  iControlAPI.searchCar(car.getCarCode(),car.getPhone());
                isSearch = sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.SEARCH_CAR);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return isSearch;

    }

    @Override
    public Boolean seatLock(RentalAccountPackage rentalAccountPackage) {

       /* RentalEBike carTest=new RentalEBike();
        carTest.setCarCode("869583076507735");
        carTest.setPhone("583076507735");
        carService.seatLock(carTest);*/
        RentalAccountPackage accountPackage = rentalAccountPackageMapper.selectById(rentalAccountPackage.getId());
        if (accountPackage != null) {
            if (accountPackage.getCarId() != null) {
                Boolean isseatLock = false;
                try {
                    RentalEBike car = rentalCarMapper.selectById(accountPackage.getCarId());
                    //isseatLock = iControlAPI.seatLock(car.getCarCode(), car.getPhone());
                    isseatLock = sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.SEAT_LOCK);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return isseatLock;
            }

        }
        return false;
    }

    @Override
    public Boolean seatManageLock(Long carId) {
        Boolean isseatLock = false;
        try {
            RentalEBike car = rentalCarMapper.selectById(carId);
            if (car != null) {
                isseatLock = sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.SEAT_LOCK);
                /*isseatLock = iControlAPI.seatLock(car.getCarCode(), car.getPhone());*/
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return isseatLock;
    }


    @Override
    public Boolean setVolume(Long carId, Integer volume) {
        Boolean isseatLock = false;
        try {
            RentalEBike car = rentalCarMapper.selectById(carId);
            if (car != null) {
                //isseatLock = iControlAPI.setVolume(car.getCarCode(), car.getPhone(), volume);
                isseatLock = sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.SET_VOLUME);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return isseatLock;
    }

    /*位置查询*/

    @Override
    public Result queryLocation(RentalEBike car) {
        try {
            //return iControlAPI.queryLocation(car.getCarCode(), car.getPhone());
            Boolean isQuery = sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.QUERY_LOCATION);
            return Result.OK(isQuery);
        } catch (Exception e) {
            return Result.error("位置查询失败: " + e.getMessage());
        }
    }

    @Override
    public Result queryControl(String address) {
        try {
            String isquery = iControlAPI.queryControlByaddress(address);
            return Result.OK(isquery);
        } catch (Exception e) {
            return Result.error("位置查询失败: " + e.getMessage());
        }
    }

    @Override
    public Result queryLocation(Object param) {
        RentalEBike car = null;
        try {
            if (param instanceof RentalAccountPackage) {
                RentalAccountPackage rentalAccountPackage = (RentalAccountPackage) param;
                RentalAccountPackage accountPackage = rentalAccountPackageMapper.selectById(rentalAccountPackage.getId());
                if (accountPackage != null && accountPackage.getCarId() != null) {
                    car = rentalCarMapper.selectById(accountPackage.getCarId());
                }
            } else if (param instanceof Long) {
                car = rentalCarMapper.selectById((Long) param);
            }

            if (car != null) {
                Boolean isQuery = sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.QUERY_LOCATION);
                return Result.OK(isQuery);
            }
        } catch (Exception e) {
            log.error("位置查询失败：", e);
            return Result.error("位置查询失败：" + e.getMessage());
        }
        return Result.error("车辆信息为空");
    }

    /*-------------------------------------------------------------------------------------------------------------------------------------*/
    @Override
    public Boolean setPlayAudio(Long carId, Byte audioIndex) {
        Boolean isOk = false;
        try {
            RentalEBike car = rentalCarMapper.selectById(carId);
            if (car != null) {
                isOk = iControlAPI.setPlayAudio(car.getCarCode(), car.getPhone(), audioIndex);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return isOk;
    }

    @Override
    public Boolean powerOn() {
        LoginRentalAccount rentalAccount = (LoginRentalAccount) SecurityUtils.getSubject().getPrincipal();
        RentalEBike car = rentalCarMapper.selectShareEBike(rentalAccount.getId());
        Boolean result = null;
        try {
           /* JT808MessageProcessor jt808MessageProcessor = new JT808MessageProcessor();
            String controlStr = jt808MessageProcessor.process(car.getCarCode(), car.getPhone(), MessageType.OPEN_CAR);*/
            result = sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.OPEN_CAR);
        } catch (Exception e) {
            throw new JeecgBootException(e);
        }
        return result;
    }
    @Override
    public Boolean enableManageSportMode(Boolean enable,Long carId) {
        //LoginRentalAccount rentalAccount = (LoginRentalAccount) SecurityUtils.getSubject().getPrincipal();
        RentalEBike car = rentalCarMapper.getByIdNoTenant(String.valueOf(carId));
        Boolean result = null;
        try {
             result = iControlAPI.enableSportMode(car.getCarCode(), car.getPhone(), enable);
            //String sportModeRedisKey = String.format(NATIONAL_STANDARD_SPEED_LIMIT_KEY, car.getCarCode());
            /*redisUtil.set(sportModeRedisKey, enable);
            Jt808CentralControlConfig config = new Jt808CentralControlConfig();
            config.setSpeedLimitEnabled(enable); // 设置限速开关
            result=   sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.SET_SPEED_LIMIT, config, null);*/

        } catch (Exception e) {
            throw new JeecgBootException(e);
        }
        return result;
    }

    @Override
    public Boolean enableSportMode(Boolean enable) {
        LoginRentalAccount rentalAccount = (LoginRentalAccount) SecurityUtils.getSubject().getPrincipal();
        RentalEBike car = rentalCarMapper.selectShareEBike(rentalAccount.getId());
        Boolean result = null;
        try {
            //result = iControlAPI.enableSportMode(car.getCarCode(), car.getPhone(), enable);
            String sportModeRedisKey = String.format(NATIONAL_STANDARD_SPEED_LIMIT_KEY, car.getCarCode());
            redisUtil.set(sportModeRedisKey, enable);
            Jt808CentralControlConfig config = new Jt808CentralControlConfig();
            config.setSpeedLimitEnabled(enable); // 设置限速开关
            result=   sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.SET_SPEED_LIMIT, config, null);

        } catch (Exception e) {
            throw new JeecgBootException(e);
        }
        return result;
    }




    @Override
    public Boolean startLocationTrack(Long carId, Short timeInterval, int validityPeriod) {
        try {
            RentalEBike car = rentalCarMapper.selectById(carId);
            if (car == null) {
                return false; // 或抛出异常，提示车辆不存在
            }
            return iControlAPI.startLocationTrack(car.getCarCode(), car.getPhone(), timeInterval, validityPeriod);
        } catch (Exception e) {
            log.error("启动位置跟踪失败", e);
            return false; // 或抛出异常
        }
    }

    @Override
    public Boolean powerOff() {
        LoginRentalAccount rentalAccount = (LoginRentalAccount) SecurityUtils.getSubject().getPrincipal();
        RentalEBike car = rentalCarMapper.selectShareEBike(rentalAccount.getId());
        Boolean result = null;
        try {
            //result = iControlAPI.closeCar(car.getCarCode(), car.getPhone());
            result = sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.CLOSE_CAR);
        } catch (Exception e) {
            throw new JeecgBootException(e);
        }
        return result;
    }

    @Override
    public Boolean locked() {
        LoginRentalAccount rentalAccount = (LoginRentalAccount) SecurityUtils.getSubject().getPrincipal();
        RentalEBike car = rentalCarMapper.selectShareEBike(rentalAccount.getId());
        Boolean result = null;
        try {
            //result = iControlAPI.defenseCar(car.getCarCode(), car.getPhone());
            result = sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.DEFENSE_CAR);
            ;
        } catch (Exception e) {
            throw new JeecgBootException(e);
        }
        return result;
    }

    @Override
    public Boolean unlock() {
        LoginRentalAccount rentalAccount = (LoginRentalAccount) SecurityUtils.getSubject().getPrincipal();
        RentalEBike car = rentalCarMapper.selectShareEBike(rentalAccount.getId());
        Boolean result = null;
        try {
            //result = iControlAPI.disarmingCar(car.getCarCode(), car.getPhone());
            result = sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.DISARMING_CAR);
        } catch (Exception e) {
            throw new JeecgBootException(e);
        }
        return result;
    }

    @Override
    public Boolean search() {
        LoginRentalAccount rentalAccount = (LoginRentalAccount) SecurityUtils.getSubject().getPrincipal();
        RentalEBike car = rentalCarMapper.selectShareEBike(rentalAccount.getId());
        Boolean result = null;
        try {
            //result = iControlAPI.searchCar(car.getCarCode(), car.getPhone());
            result = sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.SEARCH_CAR);
        } catch (Exception e) {
            throw new JeecgBootException(e);
        }
        return result;
    }

    @Override
    public Object unlockSeat() {
        LoginRentalAccount rentalAccount = (LoginRentalAccount) SecurityUtils.getSubject().getPrincipal();
        RentalEBike car = rentalCarMapper.selectShareEBike(rentalAccount.getId());
        Boolean result = null;
        try {
            //result = iControlAPI.seatLock(car.getCarCode(), car.getPhone());
            result = sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.SEAT_LOCK);
        } catch (Exception e) {
            throw new JeecgBootException(e);
        }
        return result;
    }

    /*增加限速开关*/

    @Override
    public Boolean setSpeedLimit(Long carId, Boolean enable) { //  修改方法名和参数
        try {
            RentalEBike car = rentalCarMapper.selectById(carId);
            if (car == null) {
                log.warn("未找到车辆信息，carId: {}", carId);
                return false;
            }
            Jt808CentralControlConfig config = new Jt808CentralControlConfig();
            config.setSpeedLimitEnabled(enable); // 设置限速开关

            return sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.SET_SPEED_LIMIT, config, null);
        } catch (Exception e) {
            log.error("设置限速失败", e);
            return false;
        }
    }

    @Override
    public boolean moveCar(String carCode) {
        boolean isOpen = false; // 定义返回值，默认未挪车成功

        // 根据 carCode 查询车辆信息
        RentalEBike car = rentalCarMapper.selectOne(new QueryWrapper<RentalEBike>().eq("car_code", carCode));

        if (car != null) {
            // 创建 JT808 消息处理器实例
            JT808MessageProcessor jt808MessageProcessor = new JT808MessageProcessor();

            // 处理车辆控制消息
            String controlStr = jt808MessageProcessor.process(car.getCarCode(), car.getPhone(), MessageType.OPEN_CAR);

            // 通过 Kafka 发送控制命令
            sendCommandViaKafka(car.getCarCode(), car.getPhone(), MessageType.OPEN_CAR);

            // 判断控制命令是否成功（可根据具体逻辑，例如 controlStr 的内容判断）
            if (controlStr != null && !controlStr.isEmpty()) {
                log.info("挪车成功，车辆编号: {}", carCode);
                isOpen = true; // 设置为成功
            } else {
                log.warn("挪车失败，控制命令未生成，车辆编号: {}", carCode);
            }
        } else {
            log.error("未找到车辆信息，无法挪车，车辆编号: {}", carCode);
        }

        return isOpen;
    }


    private boolean sendCommandViaKafka(String carCode, String phone, MessageType messageType) {
        try {
            if (carCode == null || phone == null) {  // 校验参数
                log.warn("carCode 或 phone 为空，无法发送指令");
                return false;
            }
            JT808MessageProcessor jt808MessageProcessor = new JT808MessageProcessor();
            String controlStr = jt808MessageProcessor.process(carCode, phone, messageType);
            kafkaTemplate.send("device_send", carCode, controlStr);
            return true;
        } catch (Exception e) {
            log.error("发送 Kafka 指令失败", e);
            return false;
        }
    }

    private boolean sendCommandViaKafka(String carCode, String phone, MessageType messageType, Jt808CentralControlConfig config, ModbusParams modbusParams) {
        try {
            if (carCode == null || phone == null) {
                log.warn("carCode 或 phone 为空，无法发送指令");
                return false;
            }
            JT808MessageProcessor jt808MessageProcessor = new JT808MessageProcessor();
            String controlStr = jt808MessageProcessor.process(carCode,phone, messageType,   config) ;
            kafkaTemplate.send("device_send", carCode, controlStr);
            return true;
        } catch (Exception e) {
            log.error("发送 Kafka 指令失败", e);
            return false;
        }
    }


}

